package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.asserts.Asserts;
import com.hmdp.constant.RedisConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.exception.BusinessException;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MRS
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    CacheClientUtil cacheClientUtil;

    /**
     * 获取商铺信息
     * @param id
     * @return
     */
    @Override
    public Result getShopById(Long id) {
        //解决缓存穿透
        // Shop shop = queryWithPassThrough(id);

        //逻辑过期时间解决缓存击穿
        // Shop shop = cacheClientUtil.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,
        //         id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //加锁解决缓存击穿
        // Shop shop = queryWithMutex(id);
        // Shop shop = cacheClientUtil.queryWithMutex(RedisConstants.CACHE_SHOP_KEY,
        //         id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL,
        //         TimeUnit.MINUTES);

        //逻辑过期时间解决缓存穿透
        Shop shop = cacheClientUtil.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY,
                id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL,
                TimeUnit.MINUTES);


        Optional.ofNullable(shop)
                .<BusinessException>orElseThrow(()->{
                    throw new BusinessException("店铺不存在");
                });

        //返回商户信息
        return Result.ok(shop);
    }

    /**
     * 使用逻辑过期时间解决缓存击穿
     * @param id
     * @return
     */
  /*  private Shop queryWithLogicalExpire(Long id) {
        Asserts.IS_NULL.checkNotNull(id);

        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1.从Redis中获取商铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.缓存命中
        if (StrUtil.isBlank(shopJson)) {
            //不命中，返回空值 因为热点数据肯定会在redis中
            return null;
        }

        //3.缓存命中 把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.判断是否过期 【过期时间在当前时间之后代表了没有过期】
        if (expireTime.isAfter(LocalDateTime.now())) {
            //4.1 未过期，直接返回店铺信息
            return shop;
        }
        //4.2 已过期，进行缓存重建
        //5. 缓存重建
        //5.1 获取锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //5.2 判断是否获取成功
        if (isLock) {
            //5.3 获取成功，开启独立线程，实现缓存重建
            try {
                //重建缓存 并刷新逻辑删除的时间
                // 此处无需 DoubleCheck，因为未获取到锁直接返回旧数据，能保证只有一个线程执行到此处
                shopDataToRedisTask.saveShopToRedis(id, RedisConstants.TTL_TWENTY);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                unlock(lockKey);
            }

        }

        //5.4 返回过期的商铺信息
        //6.返回数据
        return shop;
    }*/


    /**
     * 使用互斥锁解决缓存击穿
     * @param id
     * @return
     */
    /*private Shop queryWithMutex(Long id) {
        Asserts.IS_NULL.checkNotNull(id);

        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1.从Redis中获取商铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.缓存命中要判断是空值还是商铺信息
        if (StrUtil.isNotBlank(shopJson)) {
            //缓存中有，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        //空值，则直接返回
        if ("".equals(shopJson)) {
            return null;
        }

        //3.实现缓存重建
        //3.1 获取锁 lock:shop:id
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //3.2 判断是否获取成功
            if (!isLock) {
                //3.3失败 休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //3.4.获取锁成功 缓存无，查数据库
            shop = getById(id);

            //4.数据库没有 返回错误信息
            if (shop == null) {
                //返回空值  【设置过期时间，防止一种情况：当商户信息发生更改时，缓存的还是空值导致的数据不一致】
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return null;
            }
            //4.数据有 写入缓存
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //5.释放锁
            unlock(lockKey);
        }

        //6.返回数据
        return shop;
    }*/



    /**
     * 解决缓存穿透
     * @param id
     * @return
     */
    /*private Shop queryWithPassThrough(Long id) {
        Asserts.IS_NULL.checkNotNull(id);

        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //从Redis中获取商铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //缓存中有，直接返回
        //缓存命中要判断是空值还是商铺信息
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return null;
        }

        //空值，则直接返回
        if ("".equals(shopJson)) {
            return null;
        }

        //缓存无，查数据库
        Shop shop = getById(id);

        //数据库没有 返回错误信息
        if (shop == null) {
            //返回空值  【设置过期时间，防止一种情况：当商户信息发生更改时，缓存的还是空值导致的数据不一致】
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //数据有 写入缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }*/

    /**
     * redis实现互斥锁【获取锁】
     * @param key
     * @return
     */
  /*  private boolean tryLock(String key) {
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.TTL_TEN, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(ifAbsent);
    }*/

    /**
     * 释放锁
     * @param key
     */
   /* private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }*/



    /**
     * 更新商户信息，当出现异常时回滚数据库数据
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {

        Asserts.IS_NULL.checkNotNull(shop.getId());

        //更新数据库
        boolean isUpdated = updateById(shop);
        if (BooleanUtil.isFalse(isUpdated)) {
            throw new RuntimeException("数据库更新失败");
        }

        //删除缓存
        String key = RedisConstants.CACHE_SHOP_KEY;
        Boolean isDeleted = stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        if (BooleanUtil.isFalse(isDeleted)) {
            throw new RuntimeException("数据库更新成功，但是 Redis 删除失败");
        }
        return Result.ok();

    }
}
